<?php
session_save_path('sessions');
session_start();
include("include/dbconnection.php");

$sql="SELECT MAX(mediaID) from hasmedia";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$nextId = $row['MAX(mediaID)'] + 1;
$homeID = $_POST['homeID'];

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "video/msvideo")
|| ($_FILES["file"]["type"] == "video/x-ms-wmv")
|| ($_FILES["file"]["type"] == "video/quicktime"))
&& ($_FILES["file"]["size"] < 2000000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    $_SESSION["returnCode"] = "Return Code: " . $_FILES["file"]["error"];
    }
  else
    {
    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      $_SESSION["returnCode"] = $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      $file_name=$_FILES["file"]["name"];
	  $ext = end(explode('.', $file_name));

      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $nextId . '-' . $homeID . '.' . $ext);
	  
	  $mediapath = "upload/" . $nextId . '-' . $homeID . '.' . $ext;
	  	  
	  $sql="INSERT INTO hasmedia (homeID, mediaID) VALUES('$homeID', $nextId)";
	  $mediainsert = "INSERT INTO media (mediaPath) VALUES ('$mediapath')";
	  
	  if (!mysql_query($sql))
	  {
        echo $sql;
	    die('Error: ' . mysql_error());
	  }
	  
	  if (!mysql_query($mediainsert))
	  {
        echo $mediainsert;
	    die('Error: ' . mysql_error());
	  }
	  
	  
	  
      $_SESSION["returnCode"] = "File " . $_FILES["file"]["name"] . " has been uploaded successfully!";
      }
    }
  }
else
  {
  $_SESSION["returnCode"] = "Invalid file type or size";
  }
  
  header("location:updateAhomePicture.php");
?>
